import Taro from "@tarojs/taro"
import Http from "../utils/http"
import { applyToken, setLoginUser } from "../utils/index"

export default class UserService {
  private static _instance: UserService = new UserService()

  public static get instance(): UserService {
    return UserService._instance
  }

  login(
    agreement,
    _xSetContext,
    encryptedData: string,
    iv: string,
    wxCode: string,
    thenFunc: (account: any) => void,
    catchFunc: (err: any) => void,
    onWxcodeChanged: (code: any) => void
  ) {
    let doLoginWxDiet = (paramWxCode, isSessionExpired) => {
      console.log("wxCode>>>>>>>>>>>>>>>>>>", {
        paramWxCode,
        isSessionExpired,
      })
      Http.post("/diet/login/wx", {
        encryptedData,
        iv,
        code: paramWxCode,
        userAgreementVersion: agreement.USER_AGREEMENT_VERSION,
        userAgreementUrl: agreement.USER_AGREEMENT,
        privacyAgreementVersion: agreement.PRIVACY_AGREEMENT_VERSION,
        privacyAgreementUrl: agreement.PRIVACY_AGREEMENT,
      })
        .then((res: any) => {
          const { accessToken } = res.data
          let userInfo = { ...res.data }
          console.log(res.data)
          applyToken(accessToken)
          console.log("Taro.checkSession then ", userInfo)
          setLoginUser(userInfo)
          thenFunc(userInfo)
        })
        .catch((err: any) => {
          catchFunc(err)
          onWxcodeChanged && onWxcodeChanged(null)
        })
    }

    let doLoginWx = () => {
      /// 重新来一次
      Taro.login({
        success(res) {
          onWxcodeChanged && onWxcodeChanged(res.code)
          doLoginWxDiet(res.code, true)
        },
        fail(err) {
          catchFunc(err)
        },
      })
    }

    Taro.checkSession({
      success: result => {
        if (result.errMsg != "checkSession:ok") {
          // wx_session 过期，重新wx_login
          console.log("Taro.checkSession expired YES")
          doLoginWx()
        } else {
          console.log("Taro.checkSession expired NO")
          doLoginWxDiet(wxCode, false)
        }
      },
      fail(err) {
        console.log("Taro.checkSession failure", err)
        //Taro.login() //重新登录
        doLoginWx()
      },
    })
  }
}
